#include "pagenumberpreviewwidget.h"
#include "pagenumbersystemadapter.h"
#include <QVBoxLayout>
#include <QLabel>
#include <QApplication>

PageNumberPreviewWidget::PageNumberPreviewWidget(QWidget *parent)
    : QWidget(parent)
    , m_refreshTimer(new QTimer(this))
{
    setMinimumHeight(120);
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 设置刷新定时器
    m_refreshTimer->setSingleShot(true);
    m_refreshTimer->setInterval(REFRESH_DELAY_MS);
    connect(m_refreshTimer, &QTimer::timeout, this, &PageNumberPreviewWidget::refreshPreview);

    setMouseTracking(true);
}

void PageNumberPreviewWidget::setPageNumberSettings(const ProcessingSettings::PageNumberSettings& settings)
{
    if (m_settings.enabled != settings.enabled ||
        m_settings.position != settings.position ||
        m_settings.format != settings.format ||
        m_settings.font != settings.font ||
        m_settings.color != settings.color ||
        m_settings.horizontalOffset != settings.horizontalOffset ||
        m_settings.verticalOffset != settings.verticalOffset ||
        m_settings.rotation != settings.rotation ||
        m_settings.opacity != settings.opacity) {

        m_settings = settings;

        if (m_autoRefresh) {
            m_refreshTimer->start();
        }
    }
}

ProcessingSettings::PageNumberSettings PageNumberPreviewWidget::getPageNumberSettings() const
{
    return m_settings;
}

void PageNumberPreviewWidget::setSamplePage(int currentPage, int totalPages)
{
    if (m_currentPage != currentPage || m_totalPages != totalPages) {
        m_currentPage = currentPage;
        m_totalPages = totalPages;
        update();
    }
}

void PageNumberPreviewWidget::setShowGrid(bool show)
{
    if (m_showGrid != show) {
        m_showGrid = show;
        update();
    }
}

void PageNumberPreviewWidget::setAutoRefresh(bool enabled)
{
    m_autoRefresh = enabled;
}

void PageNumberPreviewWidget::refreshPreview()
{
    update();
}

void PageNumberPreviewWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setRenderHint(QPainter::TextAntialiasing);

    // 绘制背景
    drawBackground(painter);

    // 绘制页面内容
    drawPageContent(painter);

    // 绘制网格（可选）
    if (m_showGrid) {
        drawGrid(painter);
    }

    // 绘制页码
    if (m_settings.enabled) {
        drawPageNumber(painter);
    }
}

void PageNumberPreviewWidget::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    update();
}

void PageNumberPreviewWidget::drawBackground(QPainter& painter)
{
    // 绘制渐变背景
    QLinearGradient gradient(0, 0, 0, height());
    gradient.setColorAt(0, QColor(248, 249, 250));
    gradient.setColorAt(1, QColor(236, 240, 241));

    painter.fillRect(rect(), gradient);
}

void PageNumberPreviewWidget::drawPageContent(QPainter& painter)
{
    // 绘制模拟的页面内容
    QRectF contentRect = getContentRect();

    // 页面背景
    painter.fillRect(contentRect, QColor(255, 255, 255));
    painter.setPen(QPen(QColor(200, 200, 200), 1));
    painter.drawRect(contentRect);

    // 模拟文本内容
    painter.setPen(QPen(QColor(100, 100, 100), 1));
    painter.setFont(QFont("SF Pro Text", 10));

    QTextOption textOption(Qt::AlignLeft | Qt::AlignTop);
    QString sampleText = "这是一个页面内容示例。\n\n"
                        "页码设置将在此预览中实时显示效果。\n\n"
                        "您可以调整位置、字体、颜色等参数，\n"
                        "并立即看到渲染效果。";

    painter.drawText(contentRect.adjusted(20, 20, -20, -20), sampleText, textOption);
}

void PageNumberPreviewWidget::drawPageNumber(QPainter& painter)
{
    if (!m_settings.enabled) return;

    // 生成页码文本
    QString pageNumberText = m_settings.formatPageNumber(m_currentPage, m_totalPages);

    // 设置字体
    QFont font = m_settings.font;
    painter.setFont(font);

    // 计算页码位置
    QSizeF pageSize = getPageSize();
    QPointF position = calculatePageNumberPosition(pageSize);

    // 应用变换（偏移、旋转、透明度）
    applyPageNumberTransform(painter, position);

    // 绘制页码文本
    painter.setPen(m_settings.color);
    painter.drawText(QPointF(0, 0), pageNumberText);

    // 绘制位置指示器（小圆点）
    if (m_settings.opacity > 0.3) {
        painter.setOpacity(0.5);
        painter.setBrush(m_settings.color);
        painter.setPen(Qt::NoPen);
        painter.drawEllipse(position, 2, 2);
    }
}

void PageNumberPreviewWidget::drawGrid(QPainter& painter)
{
    // 绘制九宫格参考线
    painter.setOpacity(0.3);
    painter.setPen(QPen(QColor(150, 150, 150), 1, Qt::DashLine));

    QSizeF pageSize = getPageSize();
    QPointF topLeft = rect().center() - QPointF(pageSize.width() / 2, pageSize.height() / 2);

    // 垂直线
    for (int i = 1; i < 3; ++i) {
        qreal x = topLeft.x() + (pageSize.width() * i / 3.0);
        painter.drawLine(QPointF(x, topLeft.y()), QPointF(x, topLeft.y() + pageSize.height()));
    }

    // 水平线
    for (int i = 1; i < 3; ++i) {
        qreal y = topLeft.y() + (pageSize.height() * i / 3.0);
        painter.drawLine(QPointF(topLeft.x(), y), QPointF(topLeft.x() + pageSize.width(), y));
    }

    painter.setOpacity(1.0);
}

QPointF PageNumberPreviewWidget::calculatePageNumberPosition(const QSizeF& pageSize) const
{
    QRectF contentRect = getContentRect();
    QPointF center = contentRect.center();

    // 基础偏移（页面边距）
    qreal margin = 20.0;
    qreal x, y;

    // 使用适配器转换枚举，统一处理位置计算
    PagePosition unifiedPosition = PageNumberSystemAdapter::fromProcessingSettings(m_settings.position);

    // 根据统一位置枚举计算坐标
    switch (unifiedPosition) {
        case PagePosition::TopLeft:
            x = contentRect.left() + margin;
            y = contentRect.top() + margin;
            break;

        case PagePosition::TopCenter:
            x = center.x();
            y = contentRect.top() + margin;
            break;

        case PagePosition::TopRight:
            x = contentRect.right() - margin;
            y = contentRect.top() + margin;
            break;

        case PagePosition::BottomLeft:
            x = contentRect.left() + margin;
            y = contentRect.bottom() - margin;
            break;

        case PagePosition::BottomCenter:
            x = center.x();
            y = contentRect.bottom() - margin;
            break;

        case PagePosition::BottomRight:
            x = contentRect.right() - margin;
            y = contentRect.bottom() - margin;
            break;

        case PagePosition::Custom:
            // 对于自定义位置（原MiddleLeft/MiddleCenter/MiddleRight），使用居中逻辑
            x = center.x();
            y = center.y();
            break;

        default:
            x = center.x();
            y = contentRect.bottom() - margin;
            break;
    }

    // 应用用户自定义偏移
    x += m_settings.horizontalOffset;
    y += m_settings.verticalOffset;

    return QPointF(x, y);
}

QSizeF PageNumberPreviewWidget::getPageSize() const
{
    QRectF contentRect = getContentRect();
    return QSizeF(contentRect.width(), contentRect.height());
}

QRectF PageNumberPreviewWidget::getContentRect() const
{
    // 计算内容区域（居中的矩形区域）
    qreal margin = 20.0;
    return rect().adjusted(margin, margin, -margin, -margin);
}

void PageNumberPreviewWidget::applyPageNumberTransform(QPainter& painter, const QPointF& position) const
{
    // 应用透明度
    painter.setOpacity(m_settings.opacity);

    // 应用旋转（如果需要）
    if (qAbs(m_settings.rotation) > 0.1) {
        painter.translate(position);
        painter.rotate(m_settings.rotation);
        painter.translate(-position);
    }

    // 应用字符间距
    if (qAbs(m_settings.letterSpacing) > 0.01) {
        QFont font = painter.font();
        font.setLetterSpacing(QFont::AbsoluteSpacing, m_settings.letterSpacing);
        painter.setFont(font);
    }

    // 设置文本原点
    QFontMetrics fontMetrics(m_settings.font);
    QString pageNumberText = m_settings.formatPageNumber(m_currentPage, m_totalPages);
    QSize textSize = fontMetrics.size(Qt::TextSingleLine, pageNumberText);

    QPointF textOrigin = position;

    // 根据位置调整文本对齐 - 使用统一枚举
    PagePosition unifiedPosition = PageNumberSystemAdapter::fromProcessingSettings(m_settings.position);

    switch (unifiedPosition) {
        case PagePosition::TopLeft:
        case PagePosition::BottomLeft:
            textOrigin = position;
            break;

        case PagePosition::TopCenter:
        case PagePosition::BottomCenter:
            textOrigin.setX(position.x() - textSize.width() / 2.0);
            break;

        case PagePosition::TopRight:
        case PagePosition::BottomRight:
            textOrigin.setX(position.x() - textSize.width());
            break;

        case PagePosition::Custom:
            // 自定义位置使用居中对齐
            textOrigin.setX(position.x() - textSize.width() / 2.0);
            break;
    }

    textOrigin.setY(position.y() + textSize.height() / 4.0); // 基线调整

    // 设置绘制原点
    painter.setTransform(QTransform().translate(textOrigin.x(), textOrigin.y()));
}